const baseUrl = 'https://www.energy-beat.com'
// 文档 http://1.92.103.27:8000/swagger-ui.html

// 正常接口联调
export const request = ({
	url,
	data,
	header = {},
	method,
	isDialog = false
}) => {
	return new Promise((resolve, reject) => {

		const token = uni.getStorageSync('token');
		if (token) header['Authorization'] = token

		uni.request({
			url: baseUrl + url,
			data,
			header,
			method,
			timeout: 6000,
			success: res => {
				const {
					data
				} = res
				switch (+data.code) {
					case 200:
						resolve(data)
						break;
					case 302:
						uni.showModal({
							title: '提示',
							content: '登录已失效，请重新登录!',
							success: res => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/Login/index'
									})
								}
							}
						})
						break;
					case 303:
						uni.showModal({
							title: '提示',
							content: '登录已失效，请重新登录!',
							success: res => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/Login/index'
									})
								}
							}
						})
						break;
					case 500:
						uni.showToast({
							icon: 'error',
							title: '服务器错误',
							duration: 3000
						})
						reject(data)
						break;
					case -1:
						if (!isDialog) {
							uni.showToast({
								icon: 'error',
								title: data.msg,
								duration: 3000
							})
						}
						resolve(data)
						break;
					default:
						uni.showToast({
							icon: 'error',
							title: '服务器错误'
						})
						reject(data)
						break;
				}
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

// 上传文件联调
export const onUploadHttp = (url, file) => {
	return new Promise((resolve, reject) => {

		const header = {}
		const token = uni.getStorageSync('token');
		if (token) header['Authorization'] = token

		uni.uploadFile({
			url: baseUrl + url,
			filePath: file.url,
			name: 'file',
			header,
			success: res => {
				const data = JSON.parse(res.data)
				console.log(data)
				switch (+data.code) {
					case 200:
						resolve(data);
						break;
					case 302:
						reject(false);
						uni.showModal({
							title: '提示',
							content: '登录已失效，请重新前往登录!',
							showCancel: false,
							success: res => {
								uni.navigateTo({
									url: '/pages/Login/index'
								})
							}
						})
				}
			}
		})
	})
}